package com.vsl.health;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

/**
 * Created by Vsl on 2016/2/22.
 */
public class StepCounterService extends Service {
    private Thread thread;  //定义线程对象

    private long timer = 0;// 运动时间
    private long startTimer = 0;// 开始时间

    private long tempTime = 0;

    private Double distance = 0.0;// 路程：米
    private Double calories = 0.0;// 热量：卡路里
    private Double velocity = 0.0;// 速度：米每秒

    private int step_length = 0;  //步长
    private int weight = 0;       //体重
    private int total_step = 0;   //走的总步数

    public static Boolean FLAG = false;// 服务运行标志

    private SensorManager mSensorManager;// 传感器服务
    private StepDetector detector;// 传感器监听对象
    private PowerManager mPowerManager;// 电源管理服务
    private PowerManager.WakeLock mWakeLock;// 屏幕灯

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 在通知栏显示步数
    public void setNotify(String msg) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.notification);
        mRemoteViews.setTextViewText(R.id.notification_step, msg);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        mBuilder.setContent(mRemoteViews)
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())// 通知产生的时间，会在通知信息里显示
                .setTicker("正在播放")
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_a);
        Notification notify = mBuilder.build();
        startForeground(1, notify);
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        final Notification.Builder builder = new Notification.Builder(this);
//        Intent intent = new Intent(this, MainActivity.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//        builder.setContentIntent(pendingIntent);
//        builder.setContentTitle("标题");// 设置通知的标题
//        builder.setContentText("内容");// 设置通知的内容
//        builder.setSmallIcon(R.drawable.ic_a);
//        builder.setTicker("状态栏上显示");// 状态栏上显示
//        Notification notification = builder.build();
//        startForeground(1, notification);

        setNotify("未获得步数");

        Log.d("StepCounterService", "onCreate");

        // 创建监听器类，实例化监听对象
        detector = new StepDetector(this);

        // 获取传感器的服务，初始化传感器
        mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        // 注册传感器，注册监听器
        mSensorManager.registerListener(detector,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_FASTEST);

        // 电源管理服务
        mPowerManager = (PowerManager) this
                .getSystemService(Context.POWER_SERVICE);
        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                | PowerManager.ACQUIRE_CAUSES_WAKEUP, "S");
        mWakeLock.acquire();

        FLAG = true;// 标记为服务正在运行

        if (thread == null) {
            thread = new Thread() {// 子线程用于监听当前步数的变化

                @Override
                public void run() {
                    super.run();
                    int startTemp = 0;
                    int endTemp = 0;

                    long startTime = 0;
                    long endTime = 0;

                    while (FLAG) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
//                        if (temp != StepDetector.CURRENT_SETP) {
//                            temp = StepDetector.CURRENT_SETP;
//                        }

                        if (endTemp != StepDetector.CURRENT_SETP) {
                            endTemp = StepDetector.CURRENT_SETP;
                            startTime = endTime;
                            endTime = System.currentTimeMillis();
                            Log.d("endTemp", endTemp+"");

                            if (endTemp - startTemp <= 9) {
                                if (endTime - startTime > 3000) {
                                    StepDetector.CURRENT_SETP = startTemp;
                                    endTemp = startTemp;
                                }
                            }

                            if (endTemp - startTemp > 9) {
                                if (endTime - startTime > 3000) {
                                    startTemp = endTemp;
                                }
                            }
                        }

                        if (startTimer != System.currentTimeMillis()) {
                            timer = tempTime + System.currentTimeMillis()
                                    - startTimer;
                        }

                        if (endTemp - startTemp > 9) {

                            if (endTemp != total_step) {
                                countDistance();     //调用距离方法，看一下走了多远
                                countStep();          //调用步数方法
                                countOthers();      //调用热量和速度方法

                                Bundle bundle = new Bundle();
                                bundle.putString("total_step", total_step + "");
                                bundle.putString("distance", distance + "");
                                bundle.putString("calories", calories + "");
                                bundle.putString("velocity", velocity + "");
                                msg.setData(bundle);

                                MainActivity.handler.sendMessage(msg);// 通知主线程

                                setNotify(total_step + "");
                            }
                        }


//                        if (startTimer != System.currentTimeMillis()) {
//                            timer = tempTime + System.currentTimeMillis()
//                                    - startTimer;
//                        }

//                        if (temp != total_step) {
//                            countDistance();     //调用距离方法，看一下走了多远
//                            countStep();          //调用步数方法
//                            countOthers();      //调用热量和速度方法
//
//                             Bundle bundle = new Bundle();
//                            bundle.putString("total_step", total_step + "");
//                            bundle.putString("distance", distance + "");
//                            bundle.putString("calories", calories + "");
//                            bundle.putString("velocity", velocity + "");
//                            msg.setData(bundle);
//
//                            MainActivity.handler.sendMessage(msg);// 通知主线程
//
//                            setNotify(total_step + "");
//                        }

                    }
                }
            };
        } ;
        thread.start();
    }

    /**
     * 计算行走的距离
     */
    private void countDistance() {
        if (StepDetector.CURRENT_SETP % 2 == 0) {
            distance = (StepDetector.CURRENT_SETP / 2) * 3 * step_length * 0.01;
        } else {
            distance = ((StepDetector.CURRENT_SETP / 2) * 3 + 1) * step_length * 0.01;
        }
    }

    /**
     * 实际的步数
     */
    private void countStep() {
        if (StepDetector.CURRENT_SETP % 2 == 0) {
            total_step = StepDetector.CURRENT_SETP;
        } else {
            total_step = StepDetector.CURRENT_SETP + 1;
        }

        total_step = StepDetector.CURRENT_SETP;
    }

    /**
     * 热量和速度的数据
     */
    private void countOthers() {
        if (timer != 0 && distance != 0.0) {
            // 体重、距离
            // 跑步热量（kcal）＝体重（kg）×距离（公里）×1.036
            calories = weight * distance * 0.001;
            //速度velocity
            velocity = distance * 1000 / timer;
        } else {
            calories = 0.0;
            velocity = 0.0;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("StepCounterService", "onDestroy");

        FLAG = false;// 服务停止
        if (detector != null) {
            mSensorManager.unregisterListener(detector);
        }

        if (mWakeLock != null) {
            mWakeLock.release();
        }
    }
}
